package com.cn.ccp.util;

import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cn.ccp.bean.UserBean;
import com.cn.ccp.service.course.FilePathService;

public class CCPContants {
	private static Logger log = Logger.getLogger(CCPContants.class);
	public static String REGIST_PATH = System.getProperty("webapp.root")+File.separator+"WEB-INF"+File.separator+"classes"+File.separator;
	
	private static int globalIndex = 0 ;
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
	public static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
	
	public static String EVALUA_FILE_PATH = "evaluFilePath";
	public static String OUTLINE_FILE_PATH = "outlineFilePath";
	public static String SWF_FILE_NAME = "swfFileName";
	public static String VIDEO_FILE_NAME = "videoFileName";
	public static String VIDEO_FILE_TYPE = "videoFileType";
	public static String FILE_TYPE = "fileType";
	public static String COURSE_NAME = "COURSE_NAME";
	public static String GO_BAKC = "gobackpage" ;
	public static int undergraduate_year = 4 ;
	public static String DEFAULT_VEDIO_FILE_TYPE = "ogg,mp4,webm,flv,ogv";
	
	public static String SYS_PATH = System.getProperty("webapp.root");
	
	//保存事物处理结果值
	public static Map<Integer , Object> tranmitResultMap = new HashMap<Integer, Object>();
	
	//图片格式
	public static String imageLayout ;
	//openoffice软件目录
	public static String openOfficePath ;
	//pdf2swf软件目录
	public static String pdf2SwfPath ;
	//课程上传文件类型
	public static String uploadFileLayout ;
	//课程上传视频类型
	public static String uploadVideoLayout ;
	
	public static String videoWidth = "850" ;
	public static String videoHeight = "500" ;
	
	
//	private static CCPContants INSTANCE = null ;
//	
//	public static CCPContants getInstance(){
//		if(INSTANCE == null){
//			INSTANCE = new CCPContants();
//			INSTANCE.init();
//		}
//		return INSTANCE ;
//	}
	
	static{
		String path =System.getProperty("webapp.root")+"/WEB-INF/classes/config.properties";
		FileInputStream inputStrean;
		try {
			inputStrean = new FileInputStream(path);
			Properties p = new Properties();
			p.load(inputStrean);
			
			imageLayout = p.getProperty("image.layout");
			openOfficePath = p.getProperty("openoffice.path");
			pdf2SwfPath = p.getProperty("pdf2swf.path");
			uploadFileLayout = p.getProperty("upload.file.layout");
			uploadVideoLayout = p.getProperty("upload.video.layout"); 
			videoWidth = p.getProperty("video.width"); 
			videoHeight = p.getProperty("video.height"); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public synchronized static int getClobalIndex(){
		return ++globalIndex ;
	}
	
	
	public static String valueTransitionTo2(int i){
		try {
			return (String) (i < 10 ? "0" + i : i) ;
		} catch (Exception e) {
			return ""+i ;
		}
	}
	
	public static String valueTransitionTo4(int i){
		StringBuffer sb = new StringBuffer();
		for (int j = 0; j < 4 - (""+i).length(); j++) {
			sb.append("0");
		}
		sb.append(i);
		return sb.toString();
	}
	
	public static Map sortByValue(Map map) {

		// 将键值赌赢的entryset放到链表中
		List list = new LinkedList(map.entrySet());
		Collections.sort(list, new Comparator() {
			// 将链表按照值得从大到小进行排序
			public int compare(Object o1, Object o2) {
				return ((Comparable) ((Map.Entry) (o1)).getKey())
						.compareTo(((Map.Entry) (o2)).getKey());
			}
		});

		Map result = new LinkedHashMap();

		for (Iterator it = list.iterator(); it.hasNext();) {
			Map.Entry entry = (Map.Entry) it.next();
			result.put(entry.getKey(), entry.getValue());
		}
		return result;
	}
	
	public static String getCourseContentHeaderHtml(String title , String number){
		String str = //"<div class=\"accordion\" id=\"accordion1\">"+
				        "<div class=\"accordion-group\">"+
				          "<div class=\"accordion-heading\">"+
				            "<a class=\"accordion-toggle\" data-toggle=\"collapse\" data-parent=\"#accordion1\" href=\"#collapse"+number+"\">"+
				              "<i class=\"icon-resize-vertical\"></i>"+title+
				            "</a>"+
				          "</div>"+
				          "<div id=\"collapse"+number+"\" class=\"accordion-body collapse in\">"+
				            "<div class=\"accordion-inner\">"+
				                "<ol type=\"A\">fileInfo"+
//					                "<li><a href=\"courseContent.faces?chapterId="+ccid+"\" >"+fileName+"["+fileType+"]</a></li>"+
//				                    "<li>文档名称[Word]</li>"+
//				                    "<li>文档名称[视频]</li>"+
				                "</ol>"+
				            "</div>"+
				          "</div>"+
				       // "</div>"+
				     "</div>";
		return str ;
	}
	
	
	public static String getCourseContentFileInfoHtml(String fileName ,String fileType ,String ccid , String section_number){
		return "<li><a href=\"courseContent.faces?chapterId="+ccid+"&section_number="+section_number+"\" >"+fileName+"["+fileType+"]</a></li>";
	}
	
	public static boolean isToday(Date oldTime){
		Date newTime=new Date();
        //将下面的 理解成  yyyy-MM-dd 00：00：00 更好理解点
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	    String todayStr = format.format(newTime);
	    Date today = null;
		try {
			today = format.parse(todayStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	    if((today.getTime()-oldTime.getTime())<=0){ //至少是今天
	    	return true;
	    }
		return false;
	}

	
	
	public static String getCurrUserId(){
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		Object obj =  externalContext.getSession(false);
		HttpSession session = (HttpSession) obj;
		UserBean ubean = (UserBean) session.getAttribute(Contants.USER_SESSION_BEAN );
		return ""+ubean.getId();
	}
	
	public static void setValue(String key , String value){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.setAttribute(key ,value);
	}
	
	public static String getValue(String key){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		return (String) session.getAttribute(key);
	}
	public static void removeValue(String key){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.removeAttribute(key);
	}
	
	public static UserBean getUserBean(){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
//		log.info("-------------------"+session);
		return (UserBean) session.getAttribute(Contants.USER_SESSION_BEAN );
	}
	
	public static void setUserBean(UserBean bean){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.setAttribute(Contants.USER_SESSION_BEAN ,bean );
	}
	
	public static UserBean getUserBeanRequest(HttpServletRequest req){
		HttpSession session = req.getSession();
		return(UserBean) session.getAttribute(Contants.USER_SESSION_BEAN);
	}
	
	public static synchronized void copyFile(String oldPath, String newPath) {
		InputStream inStream = null;
		FileOutputStream fs = null;
	       try { 
	           int bytesum = 0; 
	           int byteread = 0; 
	           File oldfile = new File(oldPath); 
	           if (oldfile.exists()) { //文件存在时 
	        	   inStream = new FileInputStream(oldPath); //读入原文件 
	               fs = new FileOutputStream(newPath); 
	               byte[] buffer = new byte[1444]; 
	               while ( (byteread = inStream.read(buffer)) != -1) { 
	                   bytesum += byteread; //字节数 文件大小 
	                   fs.write(buffer, 0, byteread); 
	                   fs.flush();
	               } 
	              
	           } 
	       } 
	       catch (Exception e) { 
	           System.out.println("复制单个文件操作出错"); 
	           e.printStackTrace(); 
	       }finally{
	    	   try{
	    		   if(inStream != null){
	    			   inStream.close();
	    			   inStream = null;
	    		   }
	    	   }catch(Exception e){}
	    	   try{
	    		   if(fs != null){
	    			   fs.close();
	    			   fs = null;
	    		   }
	    	   }catch(Exception e){}
	       } 

	   } 

	public static boolean isImage(byte[] imageContent) {
        if (imageContent == null || imageContent.length == 0) {
            return false;
        }
        Image img = null;
        InputStream is = null;
        try {
            is = new ByteArrayInputStream(imageContent);
            img = ImageIO.read(is);
            if (img == null || img.getWidth(null) <= 0
                    || img.getHeight(null) <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }
	
	public static String getFilePath(String sectionFileUrl , FilePathService filePathService,int partition, int uid ){
		return getFilePath(sectionFileUrl , filePathService, partition,  uid , true,null);
	}
	
	public static String getFilePath(String sectionFileUrl , FilePathService filePathService,int partition, int uid ,String fileName){
		return getFilePath(sectionFileUrl , filePathService, partition,  uid , true,fileName);
	}
	
	 public static synchronized String  unZipFiles(String sectionFileUrl , FilePathService filePathService,int partition, int uid , boolean deleteFiles){  
		 	File sourseFile = null;
			if(partition !=  -1)
				sourseFile = new File(filePathService.findFilePathById(partition).getPath()+sectionFileUrl);
			else
				sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + sectionFileUrl);
			 String fileName = null;
			try{
			 	ZipFile zipFile = new ZipFile(sourseFile);//实例化ZipFile，每一个zip压缩文件都可以表示为一个ZipFile
		        //实例化一个Zip压缩文件的ZipInputStream对象，可以利用该类的getNextEntry()方法依次拿到每一个ZipEntry对象
		        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(sourseFile), Charset.forName("GBK"));
		        ZipEntry zipEntry = null;
		        File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+uid + File.separator);
				if(des.mkdir()){
					des.mkdirs();
				}
	//			log.info("create temp file derectory for user id ["+CCPContants.getUserBean().getId()+"]");
				if(deleteFiles){
					File[] tmpF = des.listFiles();
					for(File f : tmpF){
						if(f.getName().indexOf("head-image") == -1)
							f.delete();
					}
				}
		        
		         
				
		        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
		            fileName = zipEntry.getName();
		            log.info("------------fileName = "+fileName);
		            File temp = new File(des.getCanonicalPath() + File.separator + fileName);
		            if(zipEntry.isDirectory()){
		            	if (! temp.exists())
		            		temp.mkdirs();
		            }else{
		            	if (! temp.getParentFile().exists())
		            		temp.getParentFile().mkdirs();
			            OutputStream os = new FileOutputStream(temp);
			            //通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
			            InputStream is = zipFile.getInputStream(zipEntry);
			            int len = 0;
			            while ((len = is.read()) != -1)
			                os.write(len);
			            os.close();
			            is.close();
		            }
		        }
		        zipInputStream.close();
			}catch(Exception e){
				log.error("unzip file failed : ", e);
			}
	        return fileName;
	  }    
	
	
	
	public static synchronized String getFilePath(String sectionFileUrl , FilePathService filePathService,int partition, int uid , boolean deleteFiles,String fileName){
		try {

//			File sourseFile = new File("F:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\CCP\\files\\2\\854370bc-2362-4831-b221-f31d3ad2eab1.flv");
			File sourseFile = null;
			if(partition !=  -1)
				sourseFile = new File(filePathService.findFilePathById(partition).getPath()+sectionFileUrl);
			else
				sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + sectionFileUrl);
			
			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+uid + File.separator);
			if(des.mkdir()){
				des.mkdirs();
			}
//			log.info("create temp file derectory for user id ["+CCPContants.getUserBean().getId()+"]");
			if(deleteFiles){
				File[] tmpF = des.listFiles();
				for(File f : tmpF){
					if(f.getName().indexOf("head-image") == -1)
						f.delete();
				}
			}
			
			if(fileName == null)
				des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+uid + File.separator +sourseFile.getName());
			else
				des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+uid + File.separator +fileName);
			try {
				des.createNewFile();
			} catch (IOException e) { 
//				log.error("browse file failed : ", e);
			}
			BufferedInputStream inBuff = null;
		    BufferedOutputStream outBuff = null;
		    try {
		    	JNIUtil jni = new JNIUtil();
	            // 新建文件输入流并对它进行缓冲
	            inBuff = new BufferedInputStream(new FileInputStream(sourseFile));

	            // 新建文件输出流并对它进行缓冲
	            outBuff = new BufferedOutputStream(new FileOutputStream(des));

	            // 缓冲数组
	            byte buffer[]= jni.readFully(inBuff);
		        int len = buffer.length;
		        byte[] tmp = new byte[1024];
		        int tmpLength = 0;
		        for(int i=0; i*1024<len;i++){
		        	tmpLength = len - i*1024;
		        	if(tmpLength >= 1024)
		        		System.arraycopy(buffer, i*1024, tmp, 0, 1024);
		        	else
		        		System.arraycopy(buffer, i*1024, tmp, 0, tmpLength);
		        	outBuff.write(jni.decode(tmp));
		        }
	            // 刷新此缓冲的输出流
	            outBuff.flush();
		    }catch(Exception e){
		    	e.printStackTrace();
		    } finally {
	            // 关闭流
					try {
						if (inBuff != null)
							inBuff.close();
						if (outBuff != null)
							outBuff.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	        }
		    return CCPContants.SYS_PATH + "tempfile"+File.separator+uid + File.separator +sourseFile.getName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static boolean checkIsImageFile(String path){
		try {
			
			File file = new File(path);
			if (file != null) {
				FileInputStream fis = new FileInputStream(file);
				if (fis != null) {
					int len = fis.available();
					byte[] xml = new byte[len];
					fis.read(xml);
					// 现在file中的内容全读到了byte[]数组中
					// 如果文件中是文本信息那么： String str=new
					// String(xml,"utf-8");就可以得到文字内容
					return isImage(xml);
				}
			}

		} catch (Exception e) {
		}
		return false; 
	}
	public static boolean isNumber(String str){
		if(java.lang.Character.isDigit(str.charAt(0))){
		    return true;
		}
	    return false;
	}
	
	public static String copyOutline(String sourceFile,String fileName,String parentPath){
		log.info("----sourceFile = "+sourceFile);
		String filePath = CCPContants.SYS_PATH + "tempfile"+File.separator+parentPath + File.separator;
		File des = new File(filePath);
		if(des.mkdir()){
			des.mkdirs();
		}
	
		des = new File(filePath +fileName);
		try {
			log.info(des.getParentFile().getCanonicalPath());
			des.getParentFile().mkdirs();
			File[] tmpF = des.getParentFile().listFiles();
			for(File f : tmpF){
				f.delete();
			}
			log.info(des.getCanonicalPath());
			des.createNewFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		BufferedInputStream inBuff = null;
	    BufferedOutputStream outBuff = null;
	    try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(des));

            JNIUtil jni = new JNIUtil();
            // 缓冲数组
            // 缓冲数组
            byte buffer[]= jni.readFully(inBuff);
	        int len = buffer.length;
	        byte[] tmp = new byte[1024];
	        int tmpLength = 0;
	        for(int i=0; i*1024<len;i++){
	        	tmpLength = len - i*1024;
	        	if(tmpLength >= 1024)
	        		System.arraycopy(buffer, i*1024, tmp, 0, 1024);
	        	else
	        		System.arraycopy(buffer, i*1024, tmp, 0, tmpLength);
	        	outBuff.write(jni.decode(tmp));
	        }
            // 刷新此缓冲的输出流
            outBuff.flush();
	    }catch(Exception e){
	    	e.printStackTrace();
	    } finally {
            // 关闭流
				try {
					if (inBuff != null)
						inBuff.close();
					if (outBuff != null)
						outBuff.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        }
	    return fileName;
	}
	
	
	
	/**
	 * 作息时间类型
	 */
	public final static int SCHEDULE_TYPE_MORNING = 0;//早上
	public final static int SCHEDULE_TYPE_FORENOON = 1;//上午
	public final static int SCHEDULE_TYPE_AFTERNOON = 2;//下午
	public final static int SCHEDULE_TYPE_NIGHT = 3;//晚上
	
	
	public final static String COURSE_CONTENTS_ID_ARY = "COURSE_CONTENTS_ID_ARY";
	
}
